// pages/Mine/index/index.js
import S_request from '../../../utils/requestService.js';
import CONFIG from '../../../config.js';
import * as utils from '../../../utils/util.js';
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    displayNormal: "none",
    displayLogin: "none",
    userinfo: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.getSetting();
  },
  getMyCJInfo: function() {
    S_request.mine.myCJInfo((result) => {
      // console.log("result111==" + JSON.stringify(result))
      this.setData({
        myInfo: result
      })
    })
  },
  getSetting: function() {
    let self = this;
    // 获取用户信息
    wx.getSetting({
      success: res => {
        var authSetting = res.authSetting;
        if (authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          app.globalData.isAuthorize = true;
          // this.showTabbar();
          this.getUserInfo();
        } else if (authSetting['scope.userInfo'] == false) {
          // 用户已拒绝授权，再调用相关 API 或者 wx.authorize 会失败，需要引导用户到设置页面打开授权开关
          app.globalData.isAuthorize = false;
          // this.showModal();
          // this.hiddenTabbar();
        } else {
          // 未询问过用户授权，调用相关 API 或者 wx.authorize 会弹窗询问用户
          app.globalData.isAuthorize = false;
          // this.showModal();
          // this.hiddenTabbar();
        }
        self.isShowLogin();
      }
    })
  },
  isShowLogin: function() {
    console.log("isAuthorize===" + app.globalData.isAuthorize)
    if (app.globalData.isAuthorize) {
      this.getUserInfo();
      this.setData({
        displayNormal: "block",
        displayLogin: "none"
      });
    } else {
      this.setData({
        displayNormal: "none",
        displayLogin: "block"
      });
    }
  },
  getUserInfo: function() {
    wx.getUserInfo({
      success: res => {
        // 可以将 res 发送给后台解码出 unionId
        app.globalData.userInfo = res.userInfo;
        this.setData({
          userinfo: app.globalData.userInfo,
        });
        S_request.jx.updateUserInfo(res.userInfo, (result) => {
          // console.log("更新与用户信息成功====" + JSON.stringify(result));
          app.globalData.goldnum = result.goldcoin;
          this.getMyCJInfo();
        })

        // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
        // 所以此处加入 callback 以防止这种情况
        if (this.userInfoReadyCallback) {
          this.userInfoReadyCallback(res)
        }
      }
    })
  },
  onGotUserInfo: function(e) {
    let self = this;
    console.log(e.detail.errMsg)
    console.log(e.detail.userInfo)
    console.log(e.detail.rawData)
    if (!e.detail.userInfo) return;
    app.globalData.userInfo = e.detail.userInfo;
    let userInfo = e.detail.userInfo;
    S_request.jx.updateUserInfo(userInfo, (result) => {
      // console.log("更新与用户信息成功====" + JSON.stringify(result));
      app.globalData.isAuthorize = true;
      this.getMyCJInfo();
      self.setData({
        displayNormal: "block",
        displayLogin: "none",
        userinfo: app.globalData.userInfo,
        gold_num: utils.parseGoldNum(result.goldcoin)
      });
    })
  },
  cjClick: function() {
    wx.navigateTo({
      url: '../cjRecord/cjRecord',
    })
  },
  zjClick: function() {
    wx.navigateTo({
      url: '../zjRecord/zjRecord',
    })
  },
  goodClick:function() {
    wx.navigateTo({
      url: '../myGoods/myGoods',
    })
  },
  toHelp: function() {
    wx.navigateTo({
      url: '../help/help',
    })
  },
  formSubmit: function(e) {
    let formId = e.detail.formId;
    console.log('form发生了submit事件，携带数据为：', e.detail.value + ", " + e.detail.formId)
    let param = 'formId=' + formId;
    S_request.jx.tongJiNum(-1, param, (result) => {
      console.log("data====" + result);
    })
  },
  chooseAddress: function(e) {
    wx.getSetting({
      success: res => {
        var authSetting = res.authSetting;
        if (authSetting['scope.address']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
        } else if (authSetting['scope.address'] == false) {
          // 用户已拒绝授权，再调用相关 API 或者 wx.authorize 会失败，需要引导用户到设置页面打开授权开关
          wx.showModal({
            title: '提示',
            content: '请同意访问您的收获地址',
            showCancel: false,
            success: function(res) {
              if (res.confirm) {
                wx.openSetting({
                  success: (res) => {
                    /*
                     * res.authSetting = {
                     *   "scope.userInfo": true,
                     *   "scope.userLocation": true
                     * }
                     */
                  }
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        } else {
          // 未询问过用户授权，调用相关 API 或者 wx.authorize 会弹窗询问用户
        }
      }
    })


    wx.chooseAddress({
      success: (res) => {
        console.log("res===" + JSON.stringify(res));
        let address = res.provinceName + " " + res.cityName + " " + res.countyName + " " + res.detailInfo;
        // S_request.mine.submitShopInfo(id, res.telNumber, res.userName, address, (data) => {
        //   wx.showToast({
        //     title: '兑换成功',
        //     icon: 'none',
        //     duration: 2000
        //   })
        // })

      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    wx.showShareMenu({
      withShareTicket: false,
      success: function() {}
    });
    let obj = { 'pagepath': CONFIG.SHARE.path }
    S_request.jx.recordShare("-1", obj);
    return {
      title: CONFIG.SHARE.title,
      path: CONFIG.SHARE.path,
      imageUrl: CONFIG.SHARE.imageUrl,
      success: (res) => { //新版不走回调
        console.log("分享成功")
      }
    }
  }
})